<template>
	<div class="m-big">
		<div class="m-top">
			<form class="m-form">
				<el-form-item  label="费用所属月" style="width: 400px;">
					<el-config-provider :locale="locale">
						<el-date-picker v-model="form.date" type="month" value-format="YYYY-MM" placeholder="选择月" style="height: 40px;" />
					</el-config-provider>
				</el-form-item>
				<div>
					<el-button class="m-but1" @click="resetForm">重置</el-button>
					<el-button class="m-but2" @click="loadMonthly">查询</el-button>
				</div>
			</form>
		</div>
		<div class="m-below">
			<div>
				<el-table :data="data.tab" border height="200" :summary-method="getSummaries" show-summary
					style="width: 100%; margin-top: 20px">
					<el-table-column label="费用所属月" width="180">
					      <template #default="scope">
					        {{ scope.row.year }}-{{ scope.row.month }}
					      </template>
					    </el-table-column>
					<el-table-column prop="totalAmount" label="总金额" />
					<el-table-column prop="costYi" label="已付金额" />
					<el-table-column prop="costWei" label="未付金额" />
					<el-table-column prop="paymentRatio" label="缴费比例" />
					<el-table-column prop="num_costs" label="费用条数" />
					<el-table-column prop="num_houses" label="计费房屋数量" />
					<el-table-column prop="totalHouse" label="房屋总数" />
				</el-table>
			</div>
		</div>
		<div class="below">
			<div class="b-left">
				 <div id="main" ref="chartRef" style="width: 100%; height: 400px;"></div>
			</div>
		</div>
	</div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue';
import * as echarts from 'echarts';
import $http from '../router/AxiosApi';
import zhCn from 'element-plus/dist/locale/zh-cn';
const locale=zhCn
const chartRef = ref(null); // Create a ref to store the echarts instance
const data=reactive({
	tab:[]
})
const form = reactive({
	date:''
})
const resetForm=()=>{
	form.date=''
	loadMonthly()
}
const page = ref(1)
const pageSize = ref(5)
const loadMonthly = () => {
	console.log(form.date)
    $http.post(`findAllEx?currentPage=${page.value}&pageSize=${pageSize.value}`,form).then((res) => {
        console.log(res.data);
		data.tab=res.data.data.list
        // 初始化 rawData 数组
        const rawData = []

        res.data.data.list.forEach(item => {
            // 确保每个 item 包含需要的字段
            if (typeof item.costWei === 'number' && typeof item.costYi === 'number') {
                rawData.push({
                    year: item.year,
                    month: item.month,
                    costWei: item.costWei,
                    costYi: item.costYi,
					zong:item.totalAmount
                    // 还可以根据需要添加其他字段
                });
            } else {
                console.warn('Invalid data format for item:', item);
            }
        });

        console.log(rawData);

        // 计算每列的总和
        const totalData = [];
        if (rawData.length > 0) {
            const columns = ['costWei', 'costYi'];
			rawData.forEach(row => {
			    totalData.push(row.costWei+row.costYi);
			});
            console.log(totalData); // 输出总和数组
        } else {
            console.log('rawData is empty.');
        }

        console.log(totalData); // 输出每列的总和

        // 更新图表数据和重新渲染图表
        updateChart(rawData, totalData);
    }).catch((err) => {
        console.error('Error fetching data:', err);
    });
}

const updateChart = (rawData, totalData) => {
	console.log("进入："+totalData)
    // 构建 xAxis 的数据，将 year 和 month 拼接为 'yyyy-mm' 格式
    const xAxisData = rawData.map(item => `${item.year}-${item.month}`);

    const optionUpdate = {
		yAxis:{
			type:'value'
		},
        xAxis: {
            type: 'category',
            data: xAxisData
        },
		legend:{
			data:['未付','已付']
		},
        series: ['已付', '未付'].map((name, sid) => ({
            name,
            type: 'bar',
            stack: 'total',
            barWidth: '60%',
            label: {
                show: true,
                formatter: (params) => {
                    const dataIndex = params.dataIndex;
                    const value = rawData[dataIndex][name === '已付' ? 'costYi' : 'costWei'];
                    return totalData[dataIndex] <= 0 ? '0%' : (Math.round(value / totalData[dataIndex] * 1000) / 10) + '%';
                }
            },
            data: rawData.map(item => (name === '已付' ? item.costYi : item.costWei))
        }))
    };

    const myChart = echarts.init(chartRef.value);
    myChart.setOption(optionUpdate);

    // Optional: handle chart resize
    window.addEventListener('resize', () => {
        myChart.resize();
    });
};

onMounted(() => {
    loadMonthly();
});
</script>

<style scoped>
	.m-big {
		/* Add your styles here */
	}

	.m-top {
		padding: 10px;
		border-radius: 10px;
		background-color: white;
	}

	.m-form {
		display: flex;
	}

	.m-but1 {
		min-width: 100px;
		height: 40px;
		font-size: 14px;
		padding: 0 20px;
		color: #7e8087;
		background-color: #fafafa;
	}

	.m-but2 {
		margin-left: 10px;
		min-width: 100px;
		height: 40px;
		font-size: 14px;
		padding: 0 20px;
		color: #fff;
		background-color: #00c36d;
	}

	.m-bel_top {
		text-align: left;
	}

	.m-below {
		background-color: white;
		margin-top: 10px;
		padding: 10px;
		border-radius: 10px;
	}
	.below{
		margin-top: 10px;
	}
	.b-left{
		background-color: white;
		width: 100%;
		margin-right: 10px;
		border-radius: 10px;
		padding: 30px 20px;
		text-align: left;
		
	}
	.b-right{
		background-color: white;
		width: 700px;
		border-radius: 10px;
		padding: 30px 20px;
	}
	
</style>